<template>
  <div>
    <SearchContainer @search="queryList" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item name="dhmc" label="" class="">
          <a-input v-model:value="formState.dhmc" class="w-64" placeholder="单号/去向" />
        </a-form-item>

        <a-form-item name="ckmc" label="出库仓库">
          <SelectWarehouse v-model:value="formState.ckmc" class="!w-64" :max-tag-count="1" multiple />
        </a-form-item>
        <a-form-item name="dateRange" label="制单日期">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD " value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="zjm" label="" class="ml-10">
          <a-input v-model:value="formState.zjm" class="w-64" placeholder="药品名称/助记码/药品编号" />
        </a-form-item>
        <a-form-item label="状态" name="qrzt" class="w-64">
          <a-select v-model:value="formState.qrzt" placeholder="请选择" allow-clear>
            <a-select-option :value="0">待确认</a-select-option>
            <a-select-option :value="1">已确认</a-select-option>
            <a-select-option :value="2">已作废</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="absolute top-[-9999px] hidden">
        <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
        <PrintView id="printMe" :params="printData" />
      </div>
      <div class="flex">
        <a-button class="mb-2" type="primary" @click="onAdd"> 新增 </a-button>
      </div>
      <BaseTable
        :data-source="dataSource"
        fill
        :loading="loading"
        column-code="00001071"
        :pagination="{ total: page.total, current: page.current, pageSize: page.pageSize }"
        @change="onPageChange"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'ckdh'">
            <PopoverTable :config="detailConfig" :params="{ ckdh: record.ckdh }" :width="1600">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'mc'">
                  <MedicineInfo :value="{ mc: popRecord.mc, gg: popRecord.gg, cj: popRecord.cj }" />
                </template>
              </template>
              {{ record.ckdh }}
            </PopoverTable>
          </template>
          <template v-if="column.dataIndex === 'qrzt'">
            <a-tag v-if="record.qrzt === 0" color="blue">待确认</a-tag>
            <a-tag v-if="record.qrzt === 1" color="green">已确认</a-tag>
            <a-tag v-if="record.qrzt === 2" color="red">已作废</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" :disabled="record.qrzt" size="small" @click="onDetailEditOpen(record)">明细</a-button>
              <a-button type="link" :disabled="record.qrzt" size="small" @click="onEditOpen(record)">修改</a-button>
              <BaseButton confirm-text="是否确认?" type="link" size="small" :disabled="record.qrzt" @click="onConfirm(record)"> 确认出库 </BaseButton>
              <BaseButton confirm-text="是否作废此出库单?" type="text" danger size="small" :disabled="record.qrzt" @click="onClickCancel(record)">
                作废
              </BaseButton>
              <a-button type="link" size="small" @click="onPrint(record)"> 打印 </a-button>
            </a-space>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <AddModal v-model:open="addOpen" :title="Edittitle" :row-data="rowData" @success="onSuceess" />
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import SelectWarehouse from '@/components/SelectWarehouse'
import useUserStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import AddModal from './AddModal'
import PrintView from './PrintView'

const { empId } = useUserStore()
const addOpen = ref(false)
const Edittitle = ref('')
const rowData = ref({})
const router = useRouter()
const formRef = ref(null)
const dataSource = ref([])
const loading = ref(false)
const printMe = ref(null)
const printData = ref({})
const page = ref({
  total: 0,
  current: 1,
  pageSize: getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10
})
const formState = ref({
  dateRange: [dayjs(new Date().setDate(new Date().getDate() - 10)).format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  ckmc: [],
  pxlx: '',
  pxzd: '',
  qrzt: null
})
const detailConfig = ref({
  url: '/drugStorage/psiform/getOutBoundDetailList',
  columnCode: '00001072',
  rowKey: 'ckmxlsh',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      xh: index + 1
    }))
  }
})
const onSuceess = () => {
  queryList()
}
const onAdd = () => {
  rowData.value = ''
  addOpen.value = true
  Edittitle.value = '新增出库单'
}

const queryList = async () => {
  loading.value = true
  const { data, code, total } = await post('/drugStorage/psiform/getOutBoundHeadList', {
    pageNum: page.value.current,
    pageSize: page.value.pageSize,
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1],
    ...formState.value
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
    page.value.total = total
  }
}
const onClickCancel = async (record) => {
  const { code, msg } = await post('/drugStorage/psiform/doCancelOutBound', {
    ckdh: record.ckdh
  })
  if (code !== 0) return message.error(msg || '作废失败')
  queryList()
  message.success('作废成功')
}

//修改主表
const onEditOpen = (record) => {
  rowData.value = record
  addOpen.value = true
  Edittitle.value = '修改出库单'
}
//明细
const onDetailEditOpen = (record) => {
  router.push({
    path: '/drug-trace/warehouse/out-store-detail',
    query: {
      ckdh: record.ckdh
    }
  })
}
//确认
const onConfirm = async (record) => {
  const formData = {
    dh: record.ckdh,
    qrr: empId,
    operationmode: 17
  }
  const { msg, code } = await post('/drugStorage/psiform/doConfirmOutBound', formData)
  if (code !== 0) {
    message.error(msg)
    return
  }
  message.success(msg)
  queryList()
}
const onPageChange = ({ current, pageSize }, filters, sorter) => {
  page.value.current = current
  page.value.pageSize = pageSize
  if (sorter.column?.dataIndex) {
    formState.value.pxlx = sorter.order === 'ascend' ? '1' : '2'
    if (sorter.column.dataIndex === 'ckdh') {
      formState.value.pxzd = '1'
    } else if (sorter.column.dataIndex === 'qrsj') {
      formState.value.pxzd = '2'
    } else {
      formState.value.pxzd = '3'
    }
  } else {
    formState.value.pxlx = ''
  }
  queryList()
}
const onPrint = async (row) => {
  const { code, msg, data } = await post('/drugStorage/psiform/printKcGjckdList', { ckdh: row.ckdh })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
onMounted(() => {
  queryList()
})
</script>
